#include <stdio.h>
#include <stdlib.h>

#include "common.h"
#include "func_debug.h"
#include "func_file.h"
#include "func_times.h"
#include "func_version.h"

static uint64_t time_cnt[16] = {0};

int file_copy_demo(int argc, char *argv[])
{
    int  ret = 0;
    char file_path[128] = {0};

    if (argc != 2 || NULL == argv[1])
    {
        snprintf(file_path, sizeof(file_path), "%s", "../images/sumu001.jpg");
    }
    else
    {
        snprintf(file_path, sizeof(file_path), "%s", argv[1]);
    }
    // 申请内存
    time_cnt[0] = func_time_get_pts_ms();
    unsigned int buf_size = func_file_get_size(file_path);
    void *       buffer = (void *)malloc(buf_size);
    if (!buffer)
    {
        printf("[%s:%d][error]malloc for %s fail!\n", __FUNCTION__, __LINE__, file_path);
        return -1;
    }
    // 读取文件到内存
    time_cnt[1] = func_time_get_pts_ms();
    unsigned int file_size = 0;
    ret = func_file_read(file_path, buffer, buf_size, &file_size);
    if (ret < 0)
    {
        printf("[%s:%d][error]func_file_read fail!ret:%d\n", __FUNCTION__, __LINE__, ret);
        return -1;
    }

    // 写入文件
    time_cnt[2] = func_time_get_pts_ms();
    ret = func_file_write(0, "./img.jpg", buffer, file_size);
    if (ret < 0)
    {
        printf("[%s:%d][error]func_file_read fail!ret:%d\n", __FUNCTION__, __LINE__, ret);
        return -1;
    }
    time_cnt[3] = func_time_get_pts_ms();
    printf("[success]time count total %lums!mem malloc:%lu ms,fread:%lu,fwrite:%lu\n", time_cnt[3] - time_cnt[0],
           time_cnt[1] - time_cnt[0], time_cnt[2] - time_cnt[1], time_cnt[3] - time_cnt[2]);
    free(buffer);
    return 0;
}

int main(int argc, char *argv[])
{
    // 打印版本号和编译时间
    func_version(); // libcomonents.a库的版本
    // 打印参数个数（包含程序名本身）
    printf("param num is %d\n", argc);

    // 遍历并打印每个参数的值
    for (int i = 0; i < argc; ++i)
    {
        printf("[%d]=%s, ", i, argv[i]);
    }
    printf("\n");

    // 调用文件拷贝函数
    file_copy_demo(argc, argv);
    func_times();
    func_debug();

    return 0;
}
